package com.modelscope.ai.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.modelscope.ai.domain.entity.Exam;
import com.modelscope.ai.domain.entity.ExamItem;
import com.modelscope.ai.domain.vo.ExamVo;
import com.modelscope.ai.mapper.ExamItemMapper;
import com.modelscope.ai.service.ExamService;
import com.modelscope.ai.mapper.ExamMapper;
import com.modelscope.ai.utils.AssertUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 * @description 针对表【exam】的数据库操作Service实现
 * @createDate 2024-03-17 21:46:13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ExamServiceImpl extends ServiceImpl<ExamMapper, Exam> implements ExamService {

    final ExamItemMapper examItemMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submit(Long uid, Long articleId) {
        Exam one = lambdaQuery().eq(Exam::getUid, uid).eq(Exam::getArticleId, articleId).one();
        AssertUtil.isNotEmpty(one, "对不起试卷不存在");
        // 如果存在
        List<ExamItem> examItemList = examItemMapper.selectList(new LambdaQueryWrapper<ExamItem>().eq(ExamItem::getPid, one.getId()));
        // 计算一下分数
        Double score = examItemList.stream().filter(Objects::nonNull).mapToDouble(ExamItem::getScore).average().orElse(0);
        one.setScore(score);
        saveOrUpdate(one);
    }

    @Override
    public List<ExamVo> query(Long uid) {
        return getBaseMapper().query(uid);
    }

    @Override
    public List<String> queryIds(Long uid) {
        List<Exam> list = lambdaQuery().eq(Exam::getUid, uid).list();
        if(CollectionUtil.isEmpty(list)){
            return new ArrayList<>();
        }

        return list.stream().map(item -> String.valueOf(item.getArticleId())).toList();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Long> ids) {
        log.info("删除试卷id:{}",ids);
        AssertUtil.isNotEmpty(ids,"id应该存在");
        // 首先删除 考试成绩
        examItemMapper.delete(new LambdaQueryWrapper<ExamItem>().in(ExamItem::getPid,ids));
        // 批量删除 ids
        removeBatchByIds(ids);
    }
}




